package auth

import (
	"github.com/gin-gonic/gin"
	v1 "go_api/app/http/controllers/api/v1"
	"go_api/app/http/models/user"
	"go_api/app/requests"
	"go_api/pkg/jwt"
	"go_api/pkg/response"
)

type SignupController struct {
	v1.BaseApiController
}

func (sc *SignupController) IsPhoneExist(c *gin.Context) {
	// 初始化对象
	request := requests.SignupPhoneExistRequest{}

	if ok := requests.ValidateErrs(
		c,
		&request,
		requests.ValidateSignupPhoneExist); !ok {
		return
	}

	// 检查数据库并返回响应
	response.Data(c, gin.H{
		"exist": user.IsPhoneExist(request.Phone),
	})
}

// IsEmailExist 检测邮箱是否已注册
func (sc *SignupController) IsEmailExist(c *gin.Context) {

	// 初始化请求对象
	request := requests.SignupEmailExistRequest{}

	if ok := requests.ValidateErrs(
		c,
		&request,
		requests.ValidateSignupEmailExist); !ok {
		return
	}

	//  检查数据库并返回响应
	response.Data(c, gin.H{
		"exist": user.IsEmailExist(request.Email),
	})
}

// SignupUsingPhone 使用手机和验证码进行注册
func (sc *SignupController) SignupUsingPhone(c *gin.Context) {
	// 表单验证
	request := requests.SignupUsingPhoneRequest{}
	if ok := requests.ValidateErrs(c, &request, requests.SignupUsingPhone); !ok {
		return
	}

	// 创建数据
	_user := user.User{
		Name:     request.Name,
		Phone:    request.Phone,
		Password: request.Password,
	}
	_user.Create()

	if _user.ID > 0 {
		token := jwt.NewJWT().IssueToken(_user.GetStringID(), _user.Name)
		response.CreatedJSON(c, gin.H{
			"token": token,
			"data":  _user,
		})

		return
	}

	response.Abort500(c, "创建失败")
}

func (sc *SignupController) SignupUsingEmail(c *gin.Context) {
	// 1. 验证表单
	request := requests.SignupUsingEmailRequest{}
	if ok := requests.ValidateErrs(c, &request, requests.SignupUsingEmail); !ok {
		return
	}

	// 2. 验证成功，创建数据
	_user := user.User{
		Name:     request.Name,
		Email:    request.Email,
		Password: request.Password,
	}
	_user.Create()

	if _user.ID > 0 {
		token := jwt.NewJWT().IssueToken(_user.GetStringID(), _user.Name)
		response.CreatedJSON(c, gin.H{
			"token": token,
			"data":  _user,
		})
		return
	}

	response.Abort500(c, "创建用户失败")
}
